package service

import (
	"context"
	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
	"gitee.com/WisdomClassroom/userInfo/glb"
	"google.golang.org/grpc/metadata"
)

func (s *Service) ListUsers(ctx context.Context, request *pb.Empty) (*pb.ListUsersResponse, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		glb.Logger.Error("no metadata")
	}
	token, err := core.UnpackTokenFromMetadata(md)
	if err != nil {
		return &pb.ListUsersResponse{Status: &pb.ResponseStatus{
			Code: core.ResponseStatusCodeNotAuth, Message: err.Error(),
		}}, nil
	}

	if !token.IsManager {
		return &pb.ListUsersResponse{Status: &pb.ResponseStatus{
			Code:    core.ResponseStatusCodeNotAuth,
			Message: "用户没有权限",
		}}, nil
	}

	users := make([]models.User, 0, 8)
	err = glb.DB.Find(&users).Error
	if err != nil {
		glb.Logger.Error(err.Error())
		return listUsersRespSvrErr, nil
	}

	usersResp := make([]*pb.UserInfo, 0, len(users))
	for _, user := range users {
		usersResp = append(usersResp, &pb.UserInfo{
			AccountID: user.AccountID,
			Name:      user.Name.String,
			Gender:    user.Gender.Int32,
			Type:      user.Type.Int32,
			IsManager: user.IsManager.Bool,
		})
	}

	return &pb.ListUsersResponse{
		Status: &pb.ResponseStatus{Code: core.ResponseStatusCodeSuccess},
		Users:  usersResp,
	}, nil
}
